package com.navercorp.pinpoint.plugin.spring.web.javax.interceptor;

import com.navercorp.pinpoint.bootstrap.interceptor.AroundInterceptor;

import javax.servlet.http.HttpServletRequest;
import org.slf4j.MDC;

public class DispatcherServletInterceptor implements AroundInterceptor {
    private static final String TOKEN_NAME = "token";

    public void before(Object target, Object[] args) {
        HttpServletRequest request = (HttpServletRequest)args[0];
        String token = getToken(request);
        String requestURI = request.getRequestURI();
        if (requestURI.contains("/reprot/print/open/client/getTemplateDataSet") && (
                token == null || "".equals(token)))
            token = getParameter(request);
        MDC.put("token", token);
    }

    public void after(Object target, Object[] args, Object result, Throwable throwable) {
        MDC.remove("token");
    }

    private String getToken(HttpServletRequest request) {
        String token = request.getParameter("access_token");
        if (token == null || "".equals(token))
            token = request.getParameter("accessToken");
        if (token == null || "".equals(token)) {
            token = request.getHeader("Authorization");
            if (token != null && !"".equals(token))
                token = token.replaceAll("Bearer", "").replaceAll("bearer", "").trim();
        }
        return token;
    }

    private String getParameter(HttpServletRequest request) {
        String params = request.getParameter("params");
        if (params != null && params.contains("token")) {
            int start = params.indexOf("token\":");
            if (start > 0) {
                String substring = params.substring(start + 7);
                String[] split = substring.split("\"");
                if (split != null && split.length > 1)
                    return split[1];
            }
        }
        return "";
    }

}
